package framework.jacob;
import java.io.File;

import util.file.fileUtil;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
public class topdf extends fileUtil {
	private ActiveXComponent wordCom = null;
	private Object wordDoc = null;
	private final Variant False = new Variant(false);
	private final Variant True = new Variant(true);
	public static void main(String[] args) {
		// System.out.println(System.getProperty("java.library.path"));
		String path = topdf.class.getClassLoader().getResource("").toString();
		path = path.substring(0, path.length() - 4);
		System.out.println(path);
		try {
			topdf d2p = new topdf();
			d2p.doc2pdf(file1, "D:\\test.ps", "D:\\test.pdf");
			boolean success = (new File("D:\\test.ps")).delete();
			if (success) {
				System.out.println("删除打印机文件成功");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public boolean openWord(String path) {
		wordCom = new ActiveXComponent("wps.Application");
		try {
			Dispatch wrdDocs = wordCom.getProperty("Documents").toDispatch();
			wordDoc = Dispatch.invoke(wrdDocs, "Open", Dispatch.Method, new Object[]{path}, new int[1]).toDispatch();
			return true;
		} catch (Exception e) {
			System.out.print("openword");
			e.printStackTrace();
		}
		return false;
	}
	public void closeWord(boolean saveOnExit) {
		if (wordCom != null) {
			wordCom.invoke("Quit", new Variant[]{});
			wordCom = null;
			ComThread.Release();
		}
	}
	public void doc2pdf(String sourcepath, String destinPSFilePath, String destinPDFFilePath) {
		if (!openWord(sourcepath)) {
			closeWord(true);
			return;
		}
		ActiveXComponent distiller = new ActiveXComponent("PDFDistiller.PDFDistiller.1");
		try {
			wordCom.setProperty("ActivePrinter", new Variant("Adobe PDF"));
			Variant Background = False;
			Variant Append = False;
			int wdPrintAllDocument = 0;
			Variant Range = new Variant(wdPrintAllDocument);
			Variant OutputFileName = new Variant(destinPSFilePath);
			Dispatch.callN((Dispatch) wordDoc, "PrintOut", new Variant[]{Background, Append, Range, OutputFileName});
			System.out.println("由word文档打印为ps文档成功！");
			Variant inputPostScriptFilePath = new Variant(destinPSFilePath);
			Variant outputPDFFilePath = new Variant(destinPDFFilePath);
			Variant PDFOption = new Variant("");
			Dispatch.callN(distiller, "FileToPDF", new Variant[]{inputPostScriptFilePath, outputPDFFilePath, PDFOption});
			System.out.println("由ps文档转换为pdf文档成功！");
		} catch (Exception e) {
			System.out.print("docToPDF");
			e.printStackTrace();
		} finally {
			closeWord(true);
		}
	}
}
